import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, Image, notification, Popconfirm, Avatar, Row, Typography } from 'antd';
import type { FromUserType, UserProps } from './src/data';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { history } from 'umi';
import type { FindUserType } from '@/services/user';
import { queryUser, removeUser } from '@/services/user';
import styles from './index.modules.less';

const { Paragraph } = Typography;

const UserManager: React.FC<UserProps> = () => {
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<FromUserType[]>([]);

  useEffect(() => {
    const getData = async () => {
      const resUSer = await queryUser();
      if (resUSer) {
        setDataSource(resUSer.data);
      }
    };
    getData();
  }, []);

  const onDelete = async (userName: string) => {
    const res = await removeUser({ userName });
    if (res) {
      const resUSer = await queryUser();
      if (resUSer) {
        setDataSource(resUSer.data);
      }
      notification.success({
        message: res.message,
      });
    }
  };

  const onEdit = async (id: string) => {
    history.push({
      pathname: '/manager/userManager/manage',
      query: { type: 'edit' },
      state: { id },
    });
  };

  const columns: ProColumns<FromUserType>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      copyable: true,
      ellipsis: true,
      tip: '标题过长会自动收缩',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      render: (userName, record) => {
        return (
          <Row justify="start" align="middle" style={{ flexFlow: 'nowrap' }}>
            {record?.avatar && (
              <Avatar
                style={{ flex: '0 0 auto', marginRight: '5px' }}
                src={<Image src={record.avatar?.[0]?.url} style={{ height: '100%' }} />}
              />
            )}
            {userName}
          </Row>
        );
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        close: { text: '关闭', status: 'Default' },
        running: { text: '运行中', status: 'Processing' },
        online: { text: '已上线', status: 'Success' },
        error: { text: '异常', status: 'Error' },
      },
    },
    {
      title: '地址',
      hideInSearch: true,
      render: (_, record) => {
        return <Paragraph copyable>{`${record.address},${record.detailAddress}`}</Paragraph>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'registerTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <a
          key="editable"
          onClick={() => {
            // eslint-disable-next-line no-underscore-dangle
            onEdit(record._id);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="top"
          title="确定删除嘛？"
          onCancel={() => onDelete(record.userName)}
          cancelButtonProps={{ type: 'primary', danger: true }}
          okText="取消"
          cancelText="是的"
          okType="default"
        >
          <Button key="view" type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const onSubmitFrom = async (params: FindUserType) => {
    const res = await queryUser(params);
    if (res) {
      setDataSource(res.data);
    }
  };

  return (
    <PageContainer className={styles.user_manager}>
      <Card>
        <Button
          type="primary"
          onClick={() => {
            history.push('/manager/userManager/manage');
          }}
        >
          新建用户
        </Button>
        <ProTable<FromUserType, FindUserType>
          dataSource={dataSource}
          columns={columns}
          actionRef={actionRef}
          // request={async () => {
          //   const res = await queryRole();
          //   if (res) {
          //     return res;
          //   }
          //   return null;
          // }}
          editable={{
            type: 'multiple',
          }}
          onSubmit={onSubmitFrom}
          rowKey={(record) => record.userName}
          search={{
            labelWidth: 'auto',
          }}
          form={{
            // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
            syncToUrl: (values, type) => {
              if (type === 'get') {
                return {
                  ...values,
                  created_at: [values.startTime, values.endTime],
                };
              }
              return values;
            },
          }}
          pagination={{
            pageSize: 5,
          }}
          dateFormatter="string"
          headerTitle="用户列表"
        />
      </Card>
    </PageContainer>
  );
};

export default UserManager;
